package com.example.fw;

import java.util.List;
import java.util.logging.Logger;

import com.gargoylesoftware.htmlunit.ThreadedRefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class AdminHelper extends HelperBase{

	private WebClient web;
	private String baseUrl;
	Logger log = Logger.getLogger("AdminHelper");

	public AdminHelper(ApplicationManager manager) {
		super(manager);
		web = new WebClient();
		web.setRefreshHandler(new ThreadedRefreshHandler());
		baseUrl = manager.getProperty("baseUrl");
	}

	public boolean userExist(String login) throws Exception {
		HtmlPage userPage = openUserPage(login);
		HtmlForm deleteForm = findUserRemovalForm(userPage);
		return deleteForm != null;
	}
	
	public void deleteUserIfExists(String login) throws Exception {
		HtmlPage userPage = openUserPage(login);
		HtmlForm deleteForm = findUserRemovalForm(userPage);
		if (deleteForm != null) {
			HtmlPage commitPage = (HtmlPage) deleteForm.getInputByValue(manager.getProperty("value.delete")).click();
			HtmlForm commitForm = findUserRemovalForm(commitPage);
			commitForm.getInputByValue("Delete Account").click();
			System.out.println("User " + login + " was successfully deleted from the system");
		} else {
			System.out.println("User " + login + " doesn't exist in the system");
		}
	}

	private HtmlPage openUserPage(String login) throws Exception {
		loginAdminIfRequired();
		String userId = manager.getHibernateHelper().getUserId(login);
		HtmlPage userPage = (HtmlPage) web.getPage(baseUrl + "/manage_user_edit_page.php?user_id=" + userId);
		return userPage;
	}

	private void loginAdminIfRequired() throws Exception {
		String adminLogin = manager.getProperty("admin.login");
		String adminPassword = manager.getProperty("admin.password");
		HtmlPage mainPage = (HtmlPage) web.getPage(baseUrl);
		HtmlForm loginForm = mainPage.getFormByName("login_form");
		if (loginForm != null) {
			loginForm.getInputByName("username").setValueAttribute(adminLogin);
			loginForm.getInputByName("password").setValueAttribute(adminPassword);
			loginForm.getInputByValue("Login").click();
		}
	}

	private HtmlForm findUserRemovalForm(HtmlPage page) {
		List<HtmlForm> forms = page.getForms();
		for (HtmlForm form : forms) {
			if ("manage_user_delete.php".equals(form.getActionAttribute())) return form; 
		}
		return null;
	}

	public void createUser(String login) {
		// TODO Auto-generated method stub
		
	}

}
